<template>
  <xdh-dialog
    :title="title"
    :width="dialogWidth"
    :draggable="draggable"
    :height="dialogHeight"
    :max-height="dialogMaxHeight"
    :closed.sync="dialogVisible"
    @on-open="dialogOpen()">
    <div v-loading="!isLoad" style="height:500px" element-loading-background="rgba(0, 0, 0, 0.2)">
      <xdh-form class="custom-form"
                ref="form"
                :data="formData"
                :model="modelData"
                :mixin="mixin"
                label-width="100px"
                :view="isView"
                :uploadProps="uploadProps"
                @on-submit="handleSubmit"
                :footer="false"
                v-if="isLoad"
                element-loading-text="拼命加载中"
                element-loading-background="rgba(0, 0, 0, 0.1)"
      >
      </xdh-form>
      <el-form :model="auditForm" label-width="80px" v-if="isLoad">
        <el-form-item label="审批结果" v-show="isAudit && clueState !== 'feedback'">
          <el-radio-group v-model="auditForm.result">
            <el-radio label="1">通过</el-radio>
            <el-radio label="0">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="this.clueRow.xfr === '1' ?'下发人' :'审批人'"
                      v-show="(!isView||isAudit) && isResult && clueState !== 'feedback'">
          <el-select placeholder="请选择" v-model="auditForm.uorg">
            <el-option
              v-for="item in uorgLIst"
              :key="item.name"
              :label="item.label"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="clueState ? '反馈意见':'审批意见'" v-show="isAudit">
          <el-input type="textarea" v-model="auditForm.bz"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div class="border-line"></div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" @click="submit">{{clueState ? '反馈':'确定'}}</el-button>
  </span>

  </xdh-dialog>
</template>

<style type="text/scss" lang="scss" scoped>
  .custom-form {
    padding: 20px;
  }
</style>

<script>
  import ajax from '@/utils/ajax'
  import {FILE_UPLOAD_PATH} from '@/config'
  import XdhForm from '../../widgets/xdh-form'
  import XdhDialog from '../../widgets/xdh-dialog'
  import formFormList from '../../base/mixin/form-form-list'
  import formCustomForm from '../../base/mixin/form-custom-form'
  import sysDictionary from '../../base/mixin/sys-dictionary'
  import {LOCAL, get} from '../../utils/storage'

  const valueRex = function (value) {
    try {
      let Fn = Function;
      return new Fn('return' + value)();
    } catch (e) {
      new Error('请输入正确json格式')
      return value
    }
  }

  const dataToModel = function (data) {
    let model = data || {}
    let value
    Object.keys(model).forEach(item => {
      value = valueRex(model[item])
      if (value) {
        model[item] = valueRex(model[item])
      }
    })
    return model
  }

  export default {
    components: {
      XdhForm,
      XdhDialog
    },
    props: {
      formId: {
        type: String
      },
      title: {
        type: String,
        default: '线索'
      },
      isViewNum: {
        type: Number
      },
      isAudit: {
        type: Boolean,
        default: false
      },
      taskId: {
        type: String,
        default: ''
      },
      clueRow: {
        type: Object,
        default: null
      },
      dialogWidth: {
        type: String,
        default: '850px'
      },
      dialogHeight: {
        type: String,
        default: '600px'
      },
      dialogMaxHeight: {
        type: String,
        default: '600px'
      },
      clueState: {
        type: String
      }
    },
    mixins: [formFormList, formCustomForm, sysDictionary],
    data() {
      return {
        loginToken: get('token', LOCAL),
        mixin: formCustomForm,
        isLoad: false,
        draggable: true,
        loading: true,
        formData: [],
        processdefinekey: null,
        modelData: null,
        isView: false,
        isResult: true,
        dialogVisible: true,
        auditForm: {
          result: '1',
          bz: '',
          uorg: ''
        }
      }
    },
    computed: {
      uploadProps() {
        return {action: FILE_UPLOAD_PATH, headers: {Authorization: this.loginToken.token}}
      }
    },
    watch: {
      'auditForm.result'(val) {
        if (val === '0') {
          this.isResult = false
          this.auditForm.uorg = ''
        } else {
          this.isResult = true
        }
      }
    },
    methods: {
      // 转换格式
      toData(originData) {
        const formData = originData || []
        // 将级联下拉框的grade转换成branches
        const gradeToBranches = (item) => {
          const grade = item.grade
          this.$set(item, 'branches', {})
          item.options.forEach(opt => {
            if (grade.useMethod === 'dictionary') {
              grade.dictionaryName = opt.name
            }
            this.$set(item.branches, opt.name, [Object.assign({}, grade)])
            if (grade.grade) {
              toData([grade])
            }
          })
        }

        // 将请求字典、请求接口、自定义数据的内容放到options进行渲染，并且对级联下拉框的内容进行处理
        const setOptions = (item, res) => {
          this.$set(item, 'options', res)
          if (item.type === 'select' && item.grade) {
            gradeToBranches(item)
          }
        }

        const toData = (data) => {
          data.forEach(item => {
            if (['select', 'checkbox', 'radio'].indexOf(item.type) > -1) {
              if (item.useMethod === 'dictionary') {
                this.getDictList({dictValue: item.dictionaryName}).then(res => {
                  setOptions(item, res)
                })
              } else if (item.useMethod === 'optionUrl') {
                ajax({
                  method: 'get',
                  url: item.optionUrl
                }).then(res => {
                  setOptions(item, res.data)
                })
              } else {
                setOptions(item, valueRex(item.methodValue))
              }
            }

            if (item.type === 'treeSelect') {
              if (item.useMethod === 'dictionary') {
                this.getTreeList({name: item.dictionaryName}).then(res => {
                  setOptions(item, res)
                })
              }
            }

            if (item.type === 'dynamic') {
              item.children.forEach(col => {
                toData(col)
              })
            }

            if (item.type === 'upload') {
              if (!item.props) {
                this.$set(item, 'props', this.uploadProps)
              } else {
                item.props = Object.assign({}, item.props, this.uploadProps)
              }
            }

            // 处理有分支触发的或者动态增减的表单项
            if (item.branches) {
              Object.keys(item.branches).forEach(branch => {
                toData(item.branches[branch])
              })
            }
          })
        };
        toData(formData);
        return formData
      },
      initCustomForm() {
        this.isView = Number.parseInt(this.isViewNum) === 1
        if (this.formId) {
          this.getFormFormList(this.formId).then(res => {
            this.formData = this.toData(JSON.parse(res.content))
            this.processdefinekey = res.processdefinekey
            if (this.taskId) {
              this.getStartVac(this.taskId).then(res => {
                this.modelData = dataToModel(res)
                this.modelData.reboot = this.clueRow && this.clueRow.processdefinitionid
                this.isLoad = true
              })
            } else {
              this.modelData = {}
              this.isLoad = true
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '无效表单模板，加载失败！'
          })
        }
      },
      cancelDialog() {
        this.dialogVisible = !this.dialogVisible
      },
      submit() {
        if (this.isViewNum !== 1 || this.isAudit) {
          this.$refs.form.submit()
        } else {
          this.cancelDialog()
        }
      },
      dialogOpen() {
        this.isLoad = false;
        this.auditForm = {
          result: '1',
          bz: '',
          uorg: ''
        }
        this.initCustomForm()
      },
      handleSubmit(model, importData) {
        // 流程信息和用户信息
        const beforeInfo = Object.assign({
          uorg: this.auditForm.uorg,
          processdefinekey: this.processdefinekey
        }, !this.taskId ? {formId: this.formId} : {})

        // 审批需要用到接口参数
        const audirInfo = Object.assign({
          processdefinitionid: this.clueRow && this.clueRow.processdefinitionid,
          processdefinitionkey: this.clueRow && this.clueRow.processdefinitionkey,
          processinstanceid: this.clueRow && this.clueRow.processinstanceid,
          taskid: this.clueRow && this.clueRow.taskid
        }, this.clueState ? {bz: this.auditForm.bz} : this.auditForm);
        let submitFun = this.isAudit ? 'passAudit' : 'startVac';
        this[submitFun](Object.assign({pkValue: this.formId}, beforeInfo, this.isAudit ? audirInfo : model)).then(res => {
          importData.forEach(data => {
            this.submitSelectedExcel(data)
          })
          this.cancelDialog()
          this.$nextTick(() => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
          })
          this.$emit('on-submit')
        }).catch(err => {
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      }
    },
    mounted() {
      this.getDictList({dictValue: 'spld'}).then(res => {
        this.uorgLIst = res
      })
    },
    created() {
    }
  }
</script>
